package suit.ui;

import java.io.IOException;
import java.util.Enumeration;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;

public class FileChooserDialog extends Screen implements Button.Clicked,
		List.Selected {

	private Screen screen;

	private Box box;
	private List list;
	private Entry entry;
	private Box btns;
	private Button ok;
	private Button cancel;

	private String directory = "file:///";
	private String filename = "";

	public FileChooserDialog(Screen screen) {
		super(screen.theme, screen.getFrameRate());
		this.screen = screen;
		box = new Box(Box.Vert, false, 10);
		box.setBorderWidth(10);
		entry = new Entry();
		list = new List();
		btns = new Box(Box.Horiz, true, 10);
		ok = new Button("OK");
		cancel = new Button("Cancel");
		btns.pack(cancel, true, true, 0);
		btns.pack(ok, true, true, 0);

		box.pack(entry, false, true, 0);
		box.pack(list, true, true, 0);
		box.pack(btns, false, true, 0);
		add(box);

		ok.connect(this);
		cancel.connect(this);
		list.connect(this);

		loadRoots();
	}

	private void loadRoots() {
		list.clear();
		Enumeration e = FileSystemRegistry.listRoots();
		while (e.hasMoreElements()) {
			String root = (String) e.nextElement();
			list.add(root);
		}
		entry.setText("");
	}

	private void loadDir(String dir) {
		list.clear();
		try {
			FileConnection fc = (FileConnection) Connector.open(dir);
			Enumeration e = fc.list();
			while (e.hasMoreElements()) {
				String res = (String) e.nextElement();
				list.add(res);
			}
			directory = dir;
			entry.setText(dir);
		} catch (IOException e) {
		}
	}

	public boolean show() {
		screen.app.setScreen(this);
		return true;
	}

	public String getFilename() {
		return filename;
	}

	private Response responseHandler;

	public void connect(Response handler) {
		this.responseHandler = handler;
	}

	interface Response {
		public void onResponse(FileChooserDialog source);
	}

	public void onClicked(Button source) {
		screen.app.setScreen(screen);
		if (responseHandler != null)
			responseHandler.onResponse(this);
	}

	public void onSelect(List source) {
		Button b = (Button) source.getSelected();
		String label = ((Label) b.getChildren().elementAt(0)).getText();
		loadDir(directory+label);
	}

}
